package com.campuscrowdsourcing.server.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campuscrowdsourcing.server.annotation.Log;
import com.campuscrowdsourcing.server.common.enums.Action;
import com.campuscrowdsourcing.server.domain.entity.TaskType;
import com.campuscrowdsourcing.server.domain.model.AjaxResult;
import com.campuscrowdsourcing.server.service.TaskTypeService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 任务类型 前端控制器
 * </p>
 *
 * @author Xinyuan Zhao
 * @since 2023-03-14
 */
@RestController
@RequestMapping("/api/taskType")
public class TaskTypeController {
    @Resource
    private TaskTypeService tasktypeService;

    @PostMapping
    @Log(title = "新增任务类型", action = Action.INSERT)
    public AjaxResult saveTaskType(@RequestBody TaskType tasktype) {
        tasktypeService.save(tasktype);
        return AjaxResult.success();
    }

    @PutMapping
    @Log(title = "编辑任务类型", action = Action.UPDATE)
    public AjaxResult updateTaskType(@RequestBody TaskType tasktype) {
        tasktypeService.updateById(tasktype);
        return AjaxResult.success();
    }


    @DeleteMapping("/{id}")
    @Log(title = "删除任务类型", action = Action.INSERT)
    public AjaxResult deleteTaskType(@PathVariable Integer id) {
        Boolean result = tasktypeService.removeById(id);
        if(result == false)
        {
            AjaxResult.fail("该任务不存在或已删除");
        }
        return AjaxResult.success();
    }

    @GetMapping
    @Log(title = "查看全部任务类型", action = Action.INSERT)
    public AjaxResult listTaskType() {
        return AjaxResult.success(tasktypeService.list());
    }

    @GetMapping("/{id}")
    @Log(title = "id查找任务类型", action = Action.INSERT)
    public AjaxResult getTaskTypeById(@PathVariable Integer id) {
        TaskType taskType = tasktypeService.getById(id);
        if(taskType == null)
        {
            return AjaxResult.fail("该任务类型已删除或不存在");
        }
        return AjaxResult.success(taskType);
    }

    @GetMapping("/page")
    @Log(title = "分页查询任务类型", action = Action.INSERT)
    public AjaxResult listTaskTypePage(@RequestParam(defaultValue = "") String name,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<TaskType> queryWrapper = new QueryWrapper<TaskType>().orderByDesc("id");
        queryWrapper.like(!"".equals(name), "name", name);
        return AjaxResult.success(tasktypeService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }
}

